package com.zhaojk.audio.controller;

import com.zhaojk.audio.entity.Word;
import com.zhaojk.audio.service.WordService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaojk
 */
@RestController
@RequestMapping("/api/word")
public class WordController {
    /** CSV文件路径（位于resources目录下）**/
    private static final String CSV_FILE_PATH = "words/fruits.csv";

    private final WordService wordService;

    public WordController(WordService wordService) {
        this.wordService = wordService;
    }

    @GetMapping("/{id}")
    public Word getWord(@PathVariable Long id) {
        return wordService.getWordById(id);
    }

    @GetMapping
    public List<Word> getAllWords() {
        return wordService.getAllWords();
    }

    @PostMapping
    public void addWord(@RequestBody Word word) {
        wordService.addWord(word);
    }

    @PutMapping("/{id}")
    public void updateWord(@PathVariable Long id, @RequestBody Word word) {
        word.setId(id);
        wordService.updateWord(word);
    }

    @DeleteMapping("/{id}")
    public void deleteWord(@PathVariable Long id) {
        wordService.deleteWord(id);
    }

    @GetMapping("/getList")
    public ResponseEntity<List<String>> getWordList() {
        try {
            // 读取CSV文件
            ClassPathResource resource = new ClassPathResource(CSV_FILE_PATH);
            List<String> words = new ArrayList<>();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(resource.getInputStream()))) {
                // 跳过表头（第一行）
                reader.readLine();

                // 读取剩余行（单词）
                String line;
                while ((line = reader.readLine()) != null) {
                    // 简单清理空白（可选）
                    String word = line.trim();
                    if (!word.isEmpty()) {
                        words.add(word);
                    }
                }
            }

            return new ResponseEntity<>(words, HttpStatus.OK);
        } catch (IOException e) {
            // 文件读取失败时返回500错误
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
